<template>
  <GenericManagement
    :dataList="recipeList"
    :columns="columns"
    :formFields="formFields"
    @add="handleAddRecipe"
    @edit="handleEditRecipe"
    @delete="handleDeleteRecipe"
    primaryKey="recipe_id"
    entityName="食谱"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import GenericManagement from '../components/GenericManagement.vue';
import axios from 'axios';

const recipeList = ref([]);

const columns = [
  { prop: 'recipe_id', label: 'ID', width: '100' },
  { prop: 'recipe_name', label: '名称', width: '120' },
  { prop: 'cooking_method', label: '烹饪方法', width: '200' },
  { prop: 'preparation_time', label: '准备时间 (分钟)', width: '120' },
  { prop: 'servings', label: '份量', width: '120' },
  { prop: 'ingredients', label: '食材', width: '200' },
  { prop: 'category', label: '类别', width: '120' }
];

const formFields = [
  { prop: 'recipe_name', label: '名称', type: 'input' },
  { prop: 'cooking_method', label: '烹饪方法', type: 'input' },
  { prop: 'preparation_time', label: '准备时间 (分钟)', type: 'input' },
  { prop: 'servings', label: '份量', type: 'input' },
  { prop: 'ingredients', label: '食材', type: 'input' },
  { prop: 'category', label: '类别', type: 'input' }
];

// 获取食谱列表
const getRecipeList = async () => {
  try {
    const response = await axios.get('http://localhost:8080/DietManagementSystem_war/admin/recipe/list');
    recipeList.value = response.data;
  } catch (error) {
    console.error('获取食谱列表失败:', error);
  }
};

// 添加食谱
const handleAddRecipe = async (newRecipe) => {
  try {
    await axios.post('http://localhost:8080/DietManagementSystem_war/admin/recipe/add', newRecipe);
    getRecipeList();
  } catch (error) {
    console.error('添加食谱失败:', error);
  }
};

// 编辑食谱
const handleEditRecipe = async (updatedRecipe) => {
  try {
    await axios.put('http://localhost:8080/DietManagementSystem_war/admin/recipe/edit', updatedRecipe);
    getRecipeList();
  } catch (error) {
    console.error('编辑食谱失败:', error);
  }
};

// 删除食谱
const handleDeleteRecipe = async (recipeId) => {
  try {
    await axios.delete(`http://localhost:8080/DietManagementSystem_war/admin/recipe/delete/${recipeId}`);
    getRecipeList();
  } catch (error) {
    console.error('删除食谱失败:', error);
  }
};

onMounted(() => {
  getRecipeList();
});
</script>

<style scoped>
</style>